package service.proxy;

import entity.Category;
import entity.Member;
import exception.DuplicateUsernameException;
import exception.UserNotFoundException;
import framework.bean.factory.ObjectFactory;
import framework.bean.factory.annotation.Component;
import framework.service.exception.ServiceException;
import framework.service.transaction.TransactionManager;
import service.MemberService;

import java.util.List;

@Component("memberService")
public class MemberServiceProxy implements MemberService {

    private MemberService memberService;

    public MemberServiceProxy() {
        memberService= (MemberService) ObjectFactory.getObject("memberServiceTarget");
    }

    @Override
    public void regist(Member member) throws DuplicateUsernameException {
        TransactionManager transactionManager= (TransactionManager) ObjectFactory.getObject("transaction");


        try {
            transactionManager.begin();

            memberService.regist(member);

            transactionManager.commit();

        } catch (DuplicateUsernameException e){
            transactionManager.rollback();
            throw e;
        } catch (Exception e) {
            transactionManager.rollback();
            throw new ServiceException(e);
        }
    }

    @Override
    public Member login(String username, String password) throws UserNotFoundException {
        TransactionManager transactionManager= (TransactionManager) ObjectFactory.getObject("transaction");

        Member member=null;

        try {
            transactionManager.begin();

            member=memberService.login(username,password);

            transactionManager.commit();

        } catch (UserNotFoundException e){
            transactionManager.rollback();
            throw e;
        } catch (Exception e) {
            transactionManager.rollback();
            throw new ServiceException(e);
        }

        return member;
    }
}
